//
//  NetConnect.m
//  by MengXY
//

#import "NetConnect.h"

static const float kImageScale = 0.5; // 图片压缩率

@interface NetConnect ()

@end

@implementation NetConnect

singleton_m(Connect)

//- (id)init
//{
//    __block id tempSelf = self;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        if ((tempSelf = [super init])) {
//            // 设置线程最大并发数
//            [TheOneQueue sharedOneQueue].maxConcurrentOperationCount = 3;
//        }
//    });
//    return self;
//}
#pragma mark - NSURLConnection
#pragma mark 异步GET
+ (void)connectWithUrl:(NSString *)urlStr timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    // 判断网络是否可用
    if ([NetConnect isConnectionAvailable]) {
        // 转码（对中文字符转码）
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@", urlStr);
        // 转URL
        NSURL *url = [NSURL URLWithString:urlStr];
        // 创建GET请求
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
        
        // 开始子线程异步请求链接
        [NSURLConnection sendAsynchronousRequest:request queue:[TheQueue sharedQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSLog(@"%@", connectionError);
            
            // 返回主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@", connectionError);
                // 如果返回错误信息，返回error block
                if (connectionError!=nil) {
                    errorBlock(connectionError);
                } else {
                    // 回调block
                    completeBlock(data);
                }
                
            });
            
            
        }];
    }else {
        errorBlock(@"net can't work");
    }
    
}



#pragma mark 异步POST
+ (void)connectWithUrl:(NSString *)urlStr param:(NSString *)param timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    
    if ([NetConnect isConnectionAvailable]) {
        
        // 1.设置请求路径
        NSURL *url = [NSURL URLWithString:urlStr];
        // 判断是否有用户登录，有登录显示购物车数据
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
        
        // 2.指定请求方式（POST）
        request.HTTPMethod = @"POST";
        
        // 3.通过请求头告诉服务器客户端的类型
        NSString *userAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERAGENT"];
        if (userAgent) {
            [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        } else {
            [request setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
        }
        
        
        // 4.设置请求体
        request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
        
        // 5.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[TheQueue sharedQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                completeBlock(data);
                
                if (connectionError!=nil) {
                    errorBlock(connectionError);
                }
            });
            
        }];
    }else {
        errorBlock(@"net can't work");
    }
}

#pragma mark 同步GET
+ (void)SynchConnectWithUrl:(NSURL *)url complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    if ([NetConnect isConnectionAvailable]) {
        /*
         1> NSURLRequestUseProtocolCachePolicy = 0, 默认的缓存策略，如果缓存不存在，直接从服务端获取。如果缓存存在，会根据response中的Cache-Control字段判断下一步操作，如:Cache-Control字段为must-revalidata,则询问服务端该数据是否有更新，无更新的话直接返回给用户缓存数据，若已更新，则请求服务端.
         
         2> NSURLRequestReloadIgnoringLocalCacheData = 1,忽略本地缓存数据，直接请求服务端.
         
         3> NSURLRequestIgnoringLocalAndRemoteCacheData = 4,忽略本地缓存，代理服务器以及其他中介，直接请求源服务端.
         
         4> NSURLRequestReloadIgnoringCacheData =NSURLRequestReloadIgnoringLocalCacheData
         
         5> NSURLRequestReturnCacheDataElseLoad= 2, 有缓存就使用，不管其有效性(即忽略Cache-Control字段), 无则请求服务端.
         */
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
        NSError *connectionError=nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&connectionError];
        
        completeBlock(data);
        
        if (connectionError!=nil) {
            errorBlock(connectionError);
        }
    }else {
        errorBlock(@"net can't work");
    }
    
}

#pragma mark 同步POST
+ (void)SynchConnectWithUrl:(NSString *)urlStr param:(NSString *)param timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    if ([NetConnect isConnectionAvailable]) {
        // 1.设置请求路径
        NSURL *url = [NSURL URLWithString:urlStr];
        // 判断是否有用户登录，有登录显示购物车数据
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
        
        // 2.指定请求方式（POST）
        request.HTTPMethod = @"POST";
        
        // 3.通过请求头告诉服务器客户端的类型
        NSString *userAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERAGENT"];
        if (userAgent) {
            [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        } else {
            [request setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
        }
        
        // 4.设置请求体
        request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
        NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        completeBlock(result);
    }else {
        errorBlock(@"net can't work");
    }
    
}

#pragma mark 同步POST Json
+ (void)SynchConnectWithUrl:(NSString *)urlStr jsonDict:(NSDictionary *)jsonDict timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    if ([NetConnect isConnectionAvailable]) {
        // 字典转为json
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
        NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
        
        // 1.设置请求路径
        NSURL *url = [NSURL URLWithString:urlStr];
        // 判断是否有用户登录，有登录显示购物车数据
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
        
        // 2.指定请求方式（POST）
        request.HTTPMethod = @"POST";
        
        // 3.通过请求头告诉服务器客户端的类型
        NSString *userAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERAGENT"];
        if (userAgent) {
            [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        } else {
            [request setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
        }
        
        [request setValue:@"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        
        // 4.设置请求体
        request.HTTPBody = tempJsonData;
        
        NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        completeBlock(result);
        
    }else {
        errorBlock(@"net can't work");
    }
    
}

#pragma mark 异步POST上传图片
+ (void)connectUploadImageWithUrl:(NSString *)urlStr params:(NSDictionary *)params complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    // 判断网络是否可用
    if ([NetConnect isConnectionAvailable]) {
        //分界线的标识符
        NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
        //根据url初始化request
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:10];
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
        //结束符 AaB03x--
        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
        //要上传的图片
        UIImage *image=[params objectForKey:@"pic"];
        //得到图片的data
        NSData* data = UIImageJPEGRepresentation(image, kImageScale);
        //http body的字符串
        NSMutableString *body=[[NSMutableString alloc] init];
        //参数的集合的所有key的集合
        NSArray *keys= [params allKeys];
        
        //遍历keys
        for(int i=0;i<[keys count];i++)
        {
            //得到当前key
            NSString *key=[keys objectAtIndex:i];
            //如果key不是pic，说明value是字符类型，比如name：Boris
            if(![key isEqualToString:@"pic"])
            {
                //添加分界线，换行
                [body appendFormat:@"%@\r\n",MPboundary];
                //添加字段名称，换2行
                [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
                //添加字段的值
                [body appendFormat:@"%@\r\n",[params objectForKey:key]];
            }
        }
        
        ////添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //声明pic字段，文件名为boris.png
        [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
        //声明上传文件的格式
        [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
        
        //声明结束符：--AaB03x--
        NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
        //声明myRequestData，用来放入http body
        NSMutableData *myRequestData=[NSMutableData data];
        //将body字符串转化为UTF8格式的二进制
        [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        //加入结束符--AaB03x--
        [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
        //设置HTTPHeader中Content-Type的值
        NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
        //设置HTTPHeader
        [request setValue:content forHTTPHeaderField:@"Content-Type"];
        //设置Content-Length
        [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
        //设置http body
        [request setHTTPBody:myRequestData];
        //http method
        [request setHTTPMethod:@"POST"];
        
        // 5.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[TheQueue sharedQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                completeBlock(data);
                
                if (connectionError!=nil) {
                    errorBlock(connectionError);
                }
            });
            
        }];
    } else {
        errorBlock(@"net can't work");
    }
}

#pragma mark 异步POST json
// NSString *param = [NSString stringWithFormat:@"updateinfo=%@&storeId=%@", dataInfoStr, storeID];
+ (void)connectWithUrl:(NSString *)urlStr jsonDict:(NSDictionary *)jsonDict timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    
    if ([NetConnect isConnectionAvailable]) {
        
        // 字典转为json
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
        NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
        
        // 1.设置请求路径
        NSURL *url = [NSURL URLWithString:urlStr];
        // 判断是否有用户登录，有登录显示购物车数据
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
        
        // 2.指定请求方式（POST）
        request.HTTPMethod = @"POST";
        
        // 3.通过请求头告诉服务器客户端的类型
        NSString *userAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERAGENT"];
        if (userAgent) {
            [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        } else {
            [request setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
        }
        
        [request setValue:@"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        
        // 4.设置请求体
        request.HTTPBody = tempJsonData;
        
        // 5.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[TheQueue sharedQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                completeBlock(data);
                
                if (connectionError!=nil) {
                    errorBlock(connectionError);
                }
            });
            
        }];
    }else {
        errorBlock(@"net can't work");
    }
}

#pragma mark - URLSession
#pragma mark 异步GET
+ (void)AsynchGetWithUrl:(NSString *)urlStr timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    // 1、判断网络是否可用
    if ([NetConnect isConnectionAvailable]) {
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];// 启动状态栏网络请求指示
        
        // 2、转码（对中文字符转码）
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        // 3、构造URL资源地址
        NSURL *url = [NSURL URLWithString:urlStr];
        // 4、创建Request请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        // 5、配置Request请求
        // 设置请求方法
        request.HTTPMethod = @"GET";
        // 设置请求超时
        request.timeoutInterval = timeout;
        // 设置头部参数
        //        [request addValue:Apikey forHTTPHeaderField:@"apikey"];
        // 通过请求头告诉服务器客户端的类型
        NSString *userAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERAGENT"];
        if (userAgent) {
            [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        } else {
            [request setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
        }
        
        
        // 6、构造NSURLSessionConfiguration
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 7、构造NSURLSession，网络会话；
        __block NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        // 8、构造NSURLSessionTask，会话任务；
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            //            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            //            NSLog(@"%@", string);
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];// 关闭状态栏网络请求指示
            
            // 任务完成，取消NSURLSession
            [session invalidateAndCancel];
            
            // 释放会话
            session = nil;
            
            // 9、解析成功，处理数据，通过GCD获取主队列，在主线程中刷新界面。
            dispatch_async(dispatch_get_main_queue(), ^{
                // 9.1、请求失败，打印错误信息
                if (error) {
                    
                    errorBlock(error);
                    
                } else {
                    
                    completeBlock(data);
                    
                }
            });
        }];
        // 10、执行任务
        [task resume];
        
    } else {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];// 关闭状态栏网络请求指示
        
        // 网络不可用
        dispatch_async(dispatch_get_main_queue(), ^{
            errorBlock(@"net can't work");
        });
    }
    
}

#pragma mark 异步POST
+ (void)AsynchPostWithUrl:(NSString *)urlStr param:(NSString *)param timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    
    // 1、判断网络是否可用
    if ([NetConnect isConnectionAvailable]) {
        
        // 2、转码（对中文字符转码）
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        // 3.设置请求路径
        NSURL *url = [NSURL URLWithString:urlStr];
        
        // 4、创建Reuest请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        // 5、配置Request
        request.timeoutInterval = timeout;
        request.HTTPMethod = @"POST";
        
        // 3.通过请求头告诉服务器客户端的类型
        NSString *userAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERAGENT"];
        if (userAgent) {
            [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        } else {
            [request setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
        }
        
        
        
        // 6.设置请求体
        request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
        // 7、构造NSURLSessionConfiguration
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 8、创建网络会话
        __block NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        
        // 9、创建会话任务
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 任务完成，取消NSURLSession
                [session invalidateAndCancel];
                
                // 释放会话
                session = nil;
                
                // 9.1、判断是否请求成功
                if (error) {
                    errorBlock(error);
                } else {
                    // 解析成功
                    completeBlock(data);
                    
                }
            });
            
        }];
        // 10、执行任务
        [task resume];
        
    }else {
        // 网络不可用
        dispatch_async(dispatch_get_main_queue(), ^{
            errorBlock(@"net can't work");
        });
    }
}


#pragma mark 异步POST Json
+ (void)AsynchPostWithUrl:(NSString *)urlStr jsonDict:(NSDictionary *)jsonDict timeoutInterval:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    
    if (![HMTool isNilWithParam:jsonDict]) {
        // 网络不可用
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"参数不能为空");
            errorBlock(@"param can't nil");
        });
        return;
    }
    
    //    XYLog(@"%@----%@----%ld----%@----%@", urlStr, jsonDict, timeout, completeBlock, errorBlock);
    
    // 1、判断网络是否可用
    if ([NetConnect isConnectionAvailable]) {
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];// 启动状态栏网络请求指示
        
        // 字典转为json
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
        NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
        
        // 1.设置请求路径
        NSURL *url = [NSURL URLWithString:urlStr];
        // 判断是否有用户登录，有登录显示购物车数据
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
        
        // 2.指定请求方式（POST）
        request.HTTPMethod = @"POST";
        
        // 3.通过请求头告诉服务器客户端的类型
        //        NSString *userAgent = [NSString stringWithFormat:@"%@,%@,%@", @"iOS", ];
        NSString *userAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERAGENT"];
        if (userAgent) {
            [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        } else {
            [request setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
        }
        
        [request setValue:@"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        
        // 4.设置请求体
        request.HTTPBody = tempJsonData;
        //        NSLog(@"=httpBody==%@", (NSString *)tempJsonData);
        
        // 7、构造NSURLSessionConfiguration
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 8、创建网络会话
        __block NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        
        // 9、创建会话任务
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];// 关闭状态来网络请求指示
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 任务完成，取消NSURLSession
                [session invalidateAndCancel];
                
                // 释放会话
                session = nil;
                
                // 9.1、判断是否请求成功
                if (error) {
                    errorBlock(error);
                } else {
                    // 解析成功
                    completeBlock(data);
                    
                }
            });
            
        }];
        // 10、执行任务
        [task resume];
        
        
    }else {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];// 关闭状态来网络请求指示
        
        // 网络不可用
        dispatch_async(dispatch_get_main_queue(), ^{
            errorBlock(@"net can't work");
            
        });
    }
}

#pragma mark 异步POST上传图片
+ (void)AsynchPostUploadImageWithUrl:(NSString *)urlStr jsonDict:(NSDictionary *)jsonDict complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    // 判断网络是否可用
    if ([NetConnect isConnectionAvailable]) {
        //分界线的标识符
        NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
        //根据url初始化request
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:10];
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
        //结束符 AaB03x--
        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
        //要上传的图片
        UIImage *image=[jsonDict objectForKey:@"pic"];
        //得到图片的data
        NSData* data = UIImageJPEGRepresentation(image, kImageScale);
        //http body的字符串
        NSMutableString *body=[[NSMutableString alloc] init];
        //参数的集合的所有key的集合
        NSArray *keys= [jsonDict allKeys];
        
        //遍历keys
        for(int i=0;i<[keys count];i++)
        {
            //得到当前key
            NSString *key=[keys objectAtIndex:i];
            //如果key不是pic，说明value是字符类型，比如name：Boris
            if(![key isEqualToString:@"pic"])
            {
                //添加分界线，换行
                [body appendFormat:@"%@\r\n",MPboundary];
                //添加字段名称，换2行
                [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
                //添加字段的值
                [body appendFormat:@"%@\r\n",[jsonDict objectForKey:key]];
            }
        }
        
        ////添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //声明pic字段，文件名为boris.png
        [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
        //声明上传文件的格式
        [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
        
        //声明结束符：--AaB03x--
        NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
        //声明myRequestData，用来放入http body
        NSMutableData *myRequestData=[NSMutableData data];
        //将body字符串转化为UTF8格式的二进制
        [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        //加入结束符--AaB03x--
        [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
        //设置HTTPHeader中Content-Type的值
        NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
        //设置HTTPHeader
        [request setValue:content forHTTPHeaderField:@"Content-Type"];
        //设置Content-Length
        [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
        //设置http body
        [request setHTTPBody:myRequestData];
        //http method
        [request setHTTPMethod:@"POST"];
        
        // 7、构造NSURLSessionConfiguration
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 8、创建网络会话
        __block NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        
        // 9、创建会话任务
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            // 任务完成，取消NSURLSession
            [session invalidateAndCancel];
            
            // 释放会话
            session = nil;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                // 9.1、判断是否请求成功
                if (error) {
                    errorBlock(error);
                } else {
                    // 解析成功
                    completeBlock(data);
                    
                }
            });
            
        }];
        // 10、执行任务
        [task resume];
        
    } else {
        errorBlock(@"net can't work");
    }
}


+ (void)AsynchPostUploadImageWithUrl:(NSString *)urlStr jsonDict:(NSDictionary *)jsonDict timeout:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    // 判断网络是否可用
    if ([NetConnect isConnectionAvailable]) {
        //分界线的标识符
        NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
        //根据url初始化request
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:timeout];
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
        //结束符 AaB03x--
        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
        //要上传的图片
        UIImage *image=[jsonDict objectForKey:@"pic"];
        //得到图片的data
        NSData* data = UIImageJPEGRepresentation(image, kImageScale);
        //http body的字符串
        NSMutableString *body=[[NSMutableString alloc] init];
        //参数的集合的所有key的集合
        NSArray *keys= [jsonDict allKeys];
        
        //遍历keys
        for(int i=0;i<[keys count];i++)
        {
            //得到当前key
            NSString *key=[keys objectAtIndex:i];
            //如果key不是pic，说明value是字符类型，比如name：Boris
            if(![key isEqualToString:@"pic"])
            {
                //添加分界线，换行
                [body appendFormat:@"%@\r\n",MPboundary];
                //添加字段名称，换2行
                [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
                //添加字段的值
                [body appendFormat:@"%@\r\n",[jsonDict objectForKey:key]];
            }
        }
        
        ////添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //声明pic字段，文件名为boris.png
        [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
        //声明上传文件的格式
        [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
        
        //声明结束符：--AaB03x--
        NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
        //声明myRequestData，用来放入http body
        NSMutableData *myRequestData=[NSMutableData data];
        //将body字符串转化为UTF8格式的二进制
        [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        //加入结束符--AaB03x--
        [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
        //设置HTTPHeader中Content-Type的值
        NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
        //设置HTTPHeader
        [request setValue:content forHTTPHeaderField:@"Content-Type"];
        //设置Content-Length
        [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
        //设置http body
        [request setHTTPBody:myRequestData];
        //http method
        [request setHTTPMethod:@"POST"];
        
        // 7、构造NSURLSessionConfiguration
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 8、创建网络会话
        __block NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        
        // 9、创建会话任务
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            // 任务完成，取消NSURLSession
            [session invalidateAndCancel];
            
            // 释放会话
            session = nil;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                // 9.1、判断是否请求成功
                if (error) {
                    errorBlock(error);
                } else {
                    // 解析成功
                    completeBlock(data);
                    
                }
            });
            
        }];
        // 10、执行任务
        [task resume];
        
    } else {
        errorBlock(@"net can't work");
    }
}

#pragma mark - 下载文件
+ (void)AsynchDownloadPatchWithUrl:(NSString *)urlStr timeout:(NSTimeInterval)timeout complete:(completeblock)completeBlock error:(errorblock)errorBlock {
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 得到session对象
    __block NSURLSession* session = [NSURLSession sharedSession];
    // 创建任务
    NSURLSessionDownloadTask* downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        //        NSLog(@"location＝%@, response ＝ %@", location, response);
        
        // 任务完成，取消NSURLSession
        [session invalidateAndCancel];
        
        // 释放会话
        session = nil;
        
        // 拼接文件路径
        NSString *cache = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
        NSString *filepath = [cache stringByAppendingPathComponent:response.suggestedFilename];
        
        //        NSLog(@"文件名%@=======文件路径%@", response.suggestedFilename, filepath);
        //
        //        NSLog(@"版本号=======%@", [response.suggestedFilename substringWithRange:NSMakeRange(6, 8)]);
        
        // 将临时文件剪切或者复制Caches文件夹
        NSFileManager *mgr = [NSFileManager defaultManager];
        
        // 移除原有补丁文件
        NSString *srcFilePath = [[NSUserDefaults standardUserDefaults] objectForKey:@"PATCH_PATH"];
        [mgr removeItemAtPath:srcFilePath error:nil];
        
        // 将文件移动到Library文件夹下
        // AtPath : 剪切前的文件路径
        // ToPath : 剪切后的文件路径
        [mgr moveItemAtPath:location.path toPath:filepath error:nil];
        // 将版本号存到本地
        //        NSLog(@"response.suggestedFilename === %@", response.suggestedFilename);
        [[NSUserDefaults standardUserDefaults] setObject:[response.suggestedFilename substringWithRange:NSMakeRange(6, 8)] forKey:@"PATCH_VERSION"];
        
        //        NSLog(@"-----%@-----", filepath);
        
        // 记录补丁文件路径
        [[NSUserDefaults standardUserDefaults] setObject:filepath forKey:@"PATCH_PATH"];
        
        
    }];
    // 开始任务
    [downloadTask resume];
    
}


#pragma mark - 判断网络是否可用
+ (BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    
    switch ([reach currentReachabilityStatus]) {
            
        case NotReachable:
            
            isExistenceNetwork = NO;
            
            NSLog(@"notReachable");
            
            break;
            
        case ReachableViaWiFi:
            
            isExistenceNetwork = YES;
            
            NSLog(@"WIFI");
            
            break;
            
        case ReachableViaWWAN:
            
            isExistenceNetwork = YES;
            
            NSLog(@"3G");
            
            break;
            
    }
    
    if (!isExistenceNetwork) {
        NSLog(@"Net Don't Work!");
        return NO;
    }
    
    return isExistenceNetwork;
    
}

//#pragma mark - 实时监测网络状态
//+ (void)realAbilityStateBlock:(netstatusblock)netStatusBlock {
//    // 监测网络情况
//    [[NSNotificationCenter defaultCenter] addObserverForName:kReachabilityChangedNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
//        
//        Reachability* curReach = [note object];
//        NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
//        NetworkStatus status = [curReach currentReachabilityStatus];
//        
//        /*
//         NotReachable = 0, 无网络连接
//         ReachableViaWiFi, Wifi
//         ReachableViaWWAN 2G/3G/4G/5G
//         */
//        
//        if (netStatusBlock) {
//            netStatusBlock(status);
//        }
//    }];
//    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
//    [reach startNotifier];
//}


@end
